<template>
  <div>
    <el-dialog title="导入信息" class="import-wrapper" :visible.sync="importDialogVisible" append-to-body width="560px" :closeOnClickModal="false">
      <el-divider style="margin: 0 0 0 0"></el-divider>
      <el-row style="margin: 15px 0px">
        <el-radio-group v-model="radio">
          <el-radio :label="1">自定义模板</el-radio>
          <el-radio :label="0">TXT(销售单据)</el-radio>
        </el-radio-group>
      </el-row>
      <el-row>
        <p style="margin: 0px 0px 5px 0px">请选择模板</p>
        <el-select size="small" v-model="templateValue" placeholder="请选择模板">
          <el-option v-for="item in templateOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-row>
      <el-row style="margin-top: 10px">
        <a href="javascript:void(0)" @click="downFile()"><i class="el-icon-download"></i>下载模板</a>
      </el-row>
      <el-row style="margin: 15px 0px">
        <p>1.标准导入模板为系统自带，请先下载该模板、在下载的文件中填写内容后导入</p>
        <p>2.如果当前选择模板的字段顺序、内容有变更，需要点击模板下方的按钮更新模板</p>
        <p>3.点击“浏览”按钮，选择需要批量开票的文件，点击“导入”</p>
        <p>4.单个文件内表格行数上限为10000条</p>
        <p>5.导入的文件格式仅支持excel，大小不得超过10M</p>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">表头行：</span> </el-col>
        <el-col :span="8">
          <el-input v-model="bth" size="small" placeholder="请输入表头行" />
        </el-col>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">是否匹配客户：</span> </el-col>
        <el-col :span="8">
          <el-select v-model="matchCustomer" placeholder="请选择" size="small">
            <el-option label="不匹配" value="0"></el-option>
            <el-option label="匹配" value="1"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">是否匹配商品：</span> </el-col>
        <el-col :span="8">
          <el-select v-model="matchProduct" placeholder="请选择" size="small">
            <el-option label="不匹配" value="0"></el-option>
            <el-option label="匹配" value="1"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin: 15px 0px">
        <el-col :span="5"><span style="line-height: 32px">是否允许覆盖：</span> </el-col>
        <el-col :span="8">
          <el-select v-model="allowOverlay" placeholder="请选择" size="small">
            <el-option label="不允许覆盖" value="0"></el-option>
            <el-option label="允许覆盖" value="1"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-input type="text" size="small" id="fileName" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="fileUpload" style="margin-left: 10px">浏览文件</el-button>
          <input size="mini" type="file" id="fileInput" @change="chooseUploadFile" accept=".xls,.xlsx" style="display: none" />
        </el-col>
        <el-col :span="4">
          <el-button type="success" size="small" style="margin-left: 10px" @click="importFn">导入</el-button>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
  </div>
</template>
<script>
import { custSearch, uploadBatchFile, templateFileDownload } from '@/api/output/batchIssue.js'
import * as XLSX from 'xlsx/xlsx.mjs'
export default {
  data() {
    return {
      importDialogVisible: false,
      radio: 1,
      templateValue: '',
      templateOptions: [],
      bth: 1,
      csv: '',
      matchCustomer: '1',
      matchProduct: '1',
      allowOverlay: '1',
    }
  },
  methods: {
    fileUpload() {
      document.getElementById('fileInput').click()
    },

    chooseUploadFile(ev) {
      var fileList = ev.target.files
      if (fileList.length == 0) {
        return
      }
      var file = fileList[0]
      if (!file) {
        this.$message({
          message: '文件打开失败',
          type: 'warning',
        })
        document.querySelector('#fileInput').value = ''
        document.querySelector('#fileName').value = ''
        return
      } else {
        if (file.size > 4 * 1024 * 1024) {
          this.$message({
            message: file.name + '文件大小超过4M',
            type: 'warning',
          })
          document.querySelector('#fileInput').value = ''
          document.querySelector('#fileName').value = ''
          return
        } else {
          var subname = file.name.split('.')
          var name = ''
          for (let q = 0; q < subname.length - 1; q++) {
            if (q != subname.length - 2) name = name + subname[q] + '.'
            else name = name + subname[q]
          }
          var hz = subname[subname.length - 1]
          if (hz == null || !(hz == 'xls' || hz == 'xlsx' || hz == 'XLS' || hz == 'XLSX')) {
            this.$message({
              message: '未识别文件' + name + '的后缀',
              type: 'error',
            })
            return
          }
          document.querySelector('#fileName').value = file.name
          this.file = file
          this.reading()
        }
      }
    },

    async reading() {
      let file = this.file

      let datas = await this.readFile(file)
      let workbook = XLSX.read(datas, { type: 'binary' }) //解析二进制格式数据

      let sheet = workbook.Sheets[workbook.SheetNames[0]] //获取第一个Sheet
      var range = XLSX.utils.decode_range(sheet['!ref'])
      var csv = ''
      var data = ''
      for (var R = range.s.r; R <= range.e.r; ++R) {
        data = ''
        for (var C = range.s.c; C <= range.e.c; ++C) {
          var val = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
          if (!val) {
            if (data === '') {
              if (C == 0) {
                data = data + ''
              } else data = data + '&aisino&' + ''
            } else data = data + '&aisino&' + ''
          } else {
            var v = val.v.toString().replace(/\r\n/g, '//r//n').replace(/\n/g, '//r//n')
            if (data === '') {
              data = data + v
            } else data = data + '&aisino&' + v
          }
        }
        var check = data.split('&aisino&')
        var isnull = false
        for (var k = 0; k < check.length; k++) {
          if (check[k] != '') {
            isnull = true
            break
          }
        }
        var hh=R+1
        if (isnull) {
          csv = csv + data +hh+ '\r\n'
        }
      }
      this.csv = csv
      console.log(this.csv);
    },

    readFile(file) {
      //文件读取
      return new Promise((resolve) => {
        let reader = new FileReader()
        reader.readAsBinaryString(file) //以二进制的方式读取
        reader.onload = (ev) => {
          resolve(ev.target.result)
        }
      })
    },
    importFn() {
      if (this.templateValue == '') {
        this.$message({
          message: '请先选择模板！',
          type: 'warning',
        })
        return
      }
      if (this.bth == null || this.bth == '') {
        this.$message({
          message: '请先填写表头行',
          type: 'warning',
        })
        return
      }
      var z_reg = /^\+?[1-9][0-9]*$/
      if (!z_reg.test(this.bth)) {
        this.$message({
          message: '表头行必须为正整数(不包括0)！',
          type: 'warning',
        })
        return
      }
      if (this.csv == '') {
        this.$message({
          message: '请先选择文件',
          type: 'warning',
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      let param = {
        tableTitle: null,
        tableValue: '',
        templateId: '',
        templateType: '11',
        matchCustomer: '',
        matchProduct: '',
        allowOverlay: '',
      }

      param.tableValue = this.csv
      param.templateId = this.templateValue
      param.tableTitle = this.bth
      param.matchCustomer = this.matchCustomer
      param.matchProduct = this.matchProduct
      param.allowOverlay = this.allowOverlay
      uploadBatchFile(param).then((res) => {
        if (res.code == 0) {
          loading.close()
          this.$message({
            message: res.data,
            type: 'success',
          })
          this.importDialogVisible = false
          this.$parent.searchFn()
        } else {
          loading.close()
          this.$message({
            message: res.data,
            type: 'error',
          })
        }
      })
    },
    downFile() {
      let fd = new FormData()
      fd.append('type', '11')
      templateFileDownload(fd)
        .then((res) => {
          if (res.code == 0) {
            let base64data = res.data
            let blob = this.dataURLtofileBlob(base64data)
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(blob, 'SAP含税模板.xlsx')
            } else {
              /* 火狐谷歌的文件下载方式 */
              const url = window.URL.createObjectURL(blob)
              const link = document.createElement('a') // 创建a标签
              link.href = url
              link.download = 'SAP含税模板.xlsx' // 文件重命名，若无需重命名，将该行删去
              link.click()
              URL.revokeObjectURL(url) // 释放内存
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch((error) => {
          this.$message.error(error.data)
        })
    },
    dataURLtofileBlob(dataURI) {
      var byteString = window.atob(dataURI) //base64 解码
      var arrayBuffer = new ArrayBuffer(byteString.length) //创建缓冲数组
      var intArray = new Uint8Array(arrayBuffer) //创建视图
      for (var i = 0; i < byteString.length; i++) {
        intArray[i] = byteString.charCodeAt(i)
      }
      return new Blob([intArray], { type: 'multipart/form-data' })
    },
  },
  created() {
    let fd = new FormData()
    fd.append('type', '11')
    custSearch(fd)
      .then((res) => {
        if (res.code == 0) {
          this.templateOptions = []
          let array = res.data
          array.forEach((element) => {
            this.templateOptions.push({
              label: element.templateName,
              value: element.id,
            })
          })
          this.templateValue = this.templateOptions[0].value
        } else {
          this.$message.error(res.message)
        }
      })
      .catch((error) => {})
  },
}
</script>
<style scoped>
.import-wrapper /deep/ .el-dialog__body {
  padding: 0px 20px 30px 20px !important;
}
.import-wrapper /deep/ .el-divider--horizontal {
  margin: 5px 0px 15px 0px !important;
}
</style>